import os
import pickle
import threading
import time
import tkinter.scrolledtext as tkst
from tkinter import *

import const
import fetch
import popup_f10
import popup_f10a
import popup_f10b
import popup_f11
import popup_f12
import win32gui
from pynput import keyboard


class Menu:
    def __init__(self):
        self.tk = Tk()
        self.tk.title('menu')
        self.tk.protocol("WM_DELETE_WINDOW", self.on_closing)
        try:
            self.pref_dict = pickle.load(open('pref', 'rb'))
        except:
            self.pref_dict = dict()
        self.MF_channel = ['', const.SIG_NONE]
        self.b1 = Button(self.tk, text='更新数据', command=self.update)
        self.b1.grid(row=0, column=0, padx=10, pady=5)
        self.b2 = Button(self.tk, text='f10窗口(f10)', command=self.show_f10_window)
        self.b2.grid(row=0, column=2, padx=(0, 10), pady=5)
        self.b4 = Button(self.tk, text='财务分析(f12)', command=self.show_f12_window)
        self.b4.grid(row=1, column=0, padx=10, pady=5)
        self.boss = IntVar()
        self.boss.set(self.get_pref('boss'))
        self.cb1 = Checkbutton(self.tk, text="boss", variable=self.boss)
        self.cb1.grid(row=1, column=1, padx=10, pady=5)
        self.b5 = Button(self.tk, text='f10补充(f10a)', command=self.show_f10a_window)
        self.b5.grid(row=1, column=2, padx=10, pady=5)
        self.b6 = Button(self.tk, text='股东变化(f10b)', command=self.show_f10b_window)
        self.b6.grid(row=2, column=0, padx=(10, 0), pady=5)
        self.b3 = Button(self.tk, text='经营分析(f11)', command=self.show_f11_window)
        self.b3.grid(row=2, column=2, padx=10, pady=5)
        self.fontsize = StringVar(self.tk)
        self.fontsize.set(self.get_pref('fontsize'))

        self.sb1 = Spinbox(self.tk, from_=5, to=25, width=5, textvariable=self.fontsize)
        self.sb1.grid(row=2, column=1, padx=(0, 10), pady=5)
        self.st = tkst.ScrolledText(master=self.tk,
                                    width=30,
                                    height=10)
        self.st.grid(row=3, column=0, rowspan=3, columnspan=3, pady=10)

        t = threading.Thread(target=self.scan_hwnd)
        t.start()
        self.alt_key = keyboard.Key.alt_l
        self.x_key = keyboard.KeyCode(char='x')
        self.ctrl_key = keyboard.Key.ctrl_r
        self.shift_key = keyboard.Key.shift_r
        self.rctrl = False
        self.topmost = True
        t1 = threading.Thread(target=self.scan_MF_hwnd)
        t1.start()

    def get_pref(self, key):
        if key in self.pref_dict:
            return self.pref_dict[key]
        return {'fontsize': '12', 'boss': 0}[key]

    def scan_MF_hwnd(self):
        while True:
            hwnd = win32gui.FindWindow('TdxW_MainFrame_Class', None)
            hWndChildList = []
            win32gui.EnumChildWindows(hwnd, lambda hWnd, param: param.append(hWnd), hWndChildList)

            for h in hWndChildList:
                title = win32gui.GetWindowText(h)
                if title.startswith('分析图表-'):
                    while True:
                        self.MF_channel[0] = win32gui.GetWindowText(h).replace('分析图表-', '').replace(' ', '')
                        time.sleep(0.3)

    def update(self):
        self.b1.config(state=DISABLED)
        t = threading.Thread(target=fetch.fetch, kwargs={'is_cli': False, 'st': self.st, 'b1': self.b1})
        t.start()

    def onKeyPress(self, key):

        if key == self.ctrl_key:
            self.rctrl = True
        elif self.boss.get() == 1 and (key == self.alt_key or key == self.x_key):
            self.MF_channel[1] = const.SIG_EXIT
            self.on_closing()
        elif self.rctrl:
            if key == self.shift_key:
                if self.topmost is True:
                    self.MF_channel[1] = const.SIG_topmost_0
                    self.topmost = False
                else:
                    self.MF_channel[1] = const.SIG_topmost_1
                    self.topmost = True

    def onKeyRelease(self, key):
        if key == self.ctrl_key:
            self.rctrl = False

    def scan_hwnd(self):
        with keyboard.Listener(on_press=self.onKeyPress, on_release=self.onKeyRelease) as listener:
            listener.join()

    def show_f10_window(self):
        self.b2.config(state=DISABLED)

        w = popup_f10.Window(self.b2, int(self.sb1.get()), self.MF_channel)

        w.run()

    def show_f10a_window(self):
        self.b5.config(state=DISABLED)

        w = popup_f10a.Window(self.b5, int(self.sb1.get()), self.MF_channel)

        w.run()

    def show_f10b_window(self):
        self.b6.config(state=DISABLED)

        w = popup_f10b.Window(self.b6, int(self.sb1.get()), self.MF_channel)

        w.run()

    def show_f11_window(self):
        self.b3.config(state=DISABLED)

        w = popup_f11.Window(self.b3, int(self.sb1.get()), self.MF_channel)

        w.run()

    def show_f12_window(self):
        self.b4.config(state=DISABLED)

        w = popup_f12.Window(self.b4, int(self.sb1.get()), self.MF_channel)

        w.run()

    def on_closing(self):
        with open('pref', 'wb') as handle:
            self.pref_dict['boss'] = self.boss.get()
            self.pref_dict['fontsize'] = self.fontsize.get()
            pickle.dump(self.pref_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)
        self.tk.quit()


if __name__ == "__main__":
    m = Menu()
    m.tk.protocol("WM_DELETE_WINDOW", m.on_closing)
    m.tk.mainloop()
    os._exit(-1)
